import JSZip from 'jszip'
import utils from '../utils'

function writeFiles(files) {
  return new Promise((resolve, reject) => {
    let filename = ''
    const result = {}
    if (!utils.isArray(files) || files.length === 0) {
      reject('Nothing to export')
    } else if (files.length == 1) {
      result.filename = files[0].filename
      result.content = new Blob([files[0].content])
      resolve(result)
    } else {
      result.filename = utils.getCommonFileBase(utils.pluck(files, 'filename')) || "output"
      // saveZipFile(filename + ".zip", files, cb)
      const zip = new JSZip()
      for (let i = 0; i < files.length; i++) {
        zip.file(files[i].filename,files[i].content)
      }
      zip.generateAsync({type:'blob'})
        .then(blob => {
          result.content = blob
          resolve(result)
        }, err => reject('压缩出错'))
    }
  })
}
export default {
  writeFiles,
}